package com.tlsy.commerce.shiro;

import com.tlsy.commerce.model.User;
import com.tlsy.commerce.model_enum.StatusEnum;
import com.tlsy.commerce.multi_tenant.TenantHolder;
import com.tlsy.commerce.service.SystemService;
import com.tlsy.commerce.utils.AppConfig;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Tlsy
 * @version commerce 0.0.1
 * @date 2017/4/19  17:01
 */
public abstract class CustomCredentialsMatcher extends HashedCredentialsMatcher {

    @Autowired
    private SystemService systemService;


    protected void setTenantInfo(String phone) throws AuthenticationException {
        User user = systemService.findUserByPhone(phone);
        if(user==null){
            throw new AuthenticationException("此Token关联的用户不存在");
        }
        if(user.getStatus() != StatusEnum.ENABLED){
            throw new AuthenticationException("用户状态不正确");
        }
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute(AppConfig.USER_SESSION, user);
        TenantHolder.setTenant(user.getId());
        SecurityUtils.getSubject().isPermitted("-1");//强制授权
    }
}
